package cn.sumpu.app.wlcity.web.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.sumpu.app.wlcity.exception.AppBusinessException;
import cn.sumpu.app.wlcity.util.Common;


public class ImageUtil {
	private final static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
	public static PictureUrl uploadImage(HttpServletRequest request,String picType)throws AppBusinessException {
		PictureUrl picUrl = new PictureUrl(); 
		try {
			MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
			
			Map<String, MultipartFile> map = re.getFileMap(); 
			List<MultipartFile> fileList = new ArrayList<MultipartFile>();
			for (Object obj : map.values()) {
				MultipartFile file = (MultipartFile) obj;
				fileList.add(file);
			}
			if (fileList.size() > 0) {
				for (int i = 0; i < fileList.size(); i++) {
					MultipartFile fj = fileList.get(i);
					String fn = fj.getOriginalFilename();
					if (null != fn && fn.length() > 0) {
						picUrl.setFileOrgName(fn);
						String formateDate = Common.getFormatDate(new Date());
						
						InputStream buffin = new ByteArrayInputStream(fj.getBytes());
						BufferedImage bi = ImageIO.read(buffin);
						if (bi != null) {
							//文件类型
							String imageType = fn.substring(fn.lastIndexOf(".") + 1);
							String uuid = UUID.randomUUID().toString();
							String savePath = "picture/"+picType+"/" + formateDate ;
							String servletPath = request.getSession().getServletContext().getRealPath("/");
							try {
								String path =  servletPath + File.separator + savePath + File.separator;
								File filePath = new File(path);   
								if (!filePath.exists()) {
									filePath.mkdirs();
								}
								String fileName = path + uuid+"."+imageType;
								File f = new File(fileName);
								FileOutputStream out = new FileOutputStream(f);
						        out.write(fj.getBytes());
						        out.close();
							} catch (Exception e) {
								if (logger.isErrorEnabled()) {
									logger.error("Save image failure!", e);
								}
								throw new AppBusinessException(e);
							}
							picUrl.setPictureUrl(savePath+"/"+uuid+"."+imageType);
							return picUrl;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppBusinessException("upload fail", e);
		}
		return null;
	}
}
